//
//  WmcCloudAlbumInfoDBManager.swift
//  YPWatermarkCamera
//
//  Created by 周诗松 on 2022/9/22.
//

import Foundation

extension WmcCloudAlbumInfoDBManager: WmcDBProtocol {
    
    static var tableName: String {
        guard let userId = WmcLoginManager.shared.yupaoAccountModel?.userId, !userId.isEmpty else {
            return ""
        }
        let name = "cloud_album_info_\(userId)"
        return name
    }

    static var dataType: [WmcDBManager.DataType] {
        return [
            .primaryKey(),
            .integer(name: "albumId"),
            .integer(name: "maxDbId"),
        ]
    }
}

// MARK: - [WmcCommonlyAddressDBManager]

struct WmcCloudAlbumInfoDBManager {
    static func insert(albumId: Int, latestPhotoId: Int, resultBlock: YPBlock.OneParam<Bool>? = nil) {
        let dataList: [WmcDBManager.InsertData] = [
            .init(column: Self.dataType[1], value: albumId),
            .init(column: Self.dataType[2], value: latestPhotoId),
        ]

        WmcDBManager.shared.insertData(tableName: Self.tableName, insertData: dataList, resultBlock: resultBlock)
    }

    static func query(resultBlock: YPBlock.OneParam<[WmcMediaTeamAlbumModel]>? = nil) {
        WmcDBManager.shared.searchCustomData(tableName: Self.tableName) { list in
            var result: [WmcMediaTeamAlbumModel] = []
            list.forEach { data in
                if let model = WmcMediaTeamAlbumModel.deserialize(from: data) {
                    result.append(model)
                }
            }
            resultBlock?(result)
        }
    }
    
    static func update(albumId: Int, latestPhotoId: Int, resultBlock: YPBlock.OneParam<Bool>? = nil) {
        let dataList: [WmcDBManager.InsertData] = [.init(column: Self.dataType[2], value: latestPhotoId)]

        WmcDBManager.shared.updateData(tableName: Self.tableName,
                                       updateData: dataList,
                                       condition: "where albumId = \"\(albumId)\"",
                                       resultBlock: resultBlock)
    }

    static func delete(model: WmcMediaTeamAlbumModel, resultBlock: YPBlock.OneParam<Bool>? = nil) {
        let condition = "where albumId = '\(model.albumId)'"
        WmcDBManager.shared.deleteCustomData(tableName: Self.tableName, condition: condition, resultBlock: resultBlock)
    }
}
